package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"pgm/internal/config"
	"pgm/internal/database"
	"pgm/internal/handler"

	"github.com/gin-gonic/gin"
)

func main() {
	// 解析命令行参数
	var configPath = flag.String("config", "./configs", "配置文件路径")
	var port = flag.Int("port", 0, "服务端口")
	var dbName = flag.String("db", "", "数据库名称")
	var dbHost = flag.String("dbhost", "", "数据库主机")
	var dbUser = flag.String("dbuser", "", "数据库用户名")
	var dbPassword = flag.String("dbpass", "", "数据库密码")
	flag.Parse()

	// 加载配置
	if err := config.LoadConfig(*configPath); err != nil {
		log.Fatalf("加载配置失败: %v", err)
	}

	// 覆盖命令行参数
	if *port != 0 {
		config.AppConfig.Server.Port = *port
	}
	if *dbName != "" {
		config.AppConfig.Database.DBName = *dbName
	}
	if *dbHost != "" {
		config.AppConfig.Database.Host = *dbHost
	}
	if *dbUser != "" {
		config.AppConfig.Database.User = *dbUser
	}
	if *dbPassword != "" {
		config.AppConfig.Database.Password = *dbPassword
	}

	// 验证必要的配置
	if config.AppConfig.Database.DBName == "" {
		log.Fatal("数据库名称不能为空，请在配置文件中设置或使用 -db 参数")
	}

	// 初始化数据库连接
	if err := database.InitDB(); err != nil {
		log.Fatalf("数据库初始化失败: %v", err)
	}
	defer database.CloseDB()

	// 设置Gin模式
	gin.SetMode(config.AppConfig.Server.Mode)

	// 创建路由
	router := gin.New()

	// 添加中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())
	router.Use(corsMiddleware())
	router.Use(requestLoggingMiddleware())

	// 设置路由
	handler.SetupRoutes(router)

	// 启动服务器
	addr := config.AppConfig.Server.Host + ":" + strconv.Itoa(config.AppConfig.Server.Port)

	log.Printf("=== PGM PostgreSQL管理平台 ===")
	log.Printf("服务器启动在: http://%s", addr)
	log.Printf("数据库: %s@%s:%d/%s",
		config.AppConfig.Database.User,
		config.AppConfig.Database.Host,
		config.AppConfig.Database.Port,
		config.AppConfig.Database.DBName)
	log.Printf("模式: %s", config.AppConfig.Server.Mode)
	log.Printf("===============================")

	// 创建HTTP服务器
	server := &http.Server{
		Addr:           addr,
		Handler:        router,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   30 * time.Second,
		MaxHeaderBytes: 1 << 20, // 1MB
	}

	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatalf("服务器启动失败: %v", err)
	}
}

// CORS中间件
func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, X-Request-With")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}

// 请求日志中间件
func requestLoggingMiddleware() gin.HandlerFunc {
	return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		return fmt.Sprintf("[%s] %s %s %d %s \"%s\" %s \"%s\"\n",
			param.TimeStamp.Format("2006-01-02 15:04:05"),
			param.Method,
			param.Path,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ClientIP,
			param.ErrorMessage,
		)
	})
}
